<?php

class Ead_PublicacaoController extends Ead_Controller_Action
{
    private $_table     = 'PUBLICACAO';
    private $_pk        = 'PBC_ID';
    private $_order_col = 'PBC_DATHOR';
    private $_order     = 'DESC';
    private $_sta_col   = 'PBC_STA';
    private $obj        = '';
    private $form       = '';
    
    
    public function init()
    {
         if($this->getRequest()->getActionName() == 'edit') $this->form = new Admin_Form_Publicacaoead();       
    }

    public function indexAction() {
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/ead/publicacao.js?1=7');
        
        //monta menu
        $sessao = new Zend_Session_Namespace('Professor');
        
        $query = 'SELECT SQL_CACHE DISTINCT p.PRS_ID, p.PRS_NOM, d.DCP_ID, d.DCP_NOM '
                .' FROM PROFESSOR p, DISCIPLINA d'
                .' WHERE p.DCP_ID = d.DCP_ID AND p.PRS_STA = 1 AND d.DCP_STA = 1'
                .' AND p.PRS_ID = '.$sessao->professor['PRS_ID']
                .' ORDER BY PRS_NOM';
        $result = $this->db->fetchAll($query); 
        $this->view->menu = $result;
        
        
        Zend_Loader::loadClass('datetools','library');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
         
        $where = $this->_pk . ' > 0';
        
        
        //$stafiltro = $this->_getParam('stafiltro', '1');      
        //if($stafiltro != '') $where .= ' and PBC_STA = ' . $stafiltro;    
        //$this->view->stafiltro = $stafiltro;
        
        $where .= ' AND USU_ID = '.$this->storage->read()->USU_ID;
       
        $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$where.' ORDER BY '.$this->_order_col.' '.$this->_order;
        $result = $this->db->fetchAll($query); 
        $this->view->result = $this->paginacao($result);
        
    }
    
    public function editAction() {
        
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('datetools','library');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        
        $this->view->headLink()->prependStylesheet($this->_urlbase.'/public/media/js/chosen/chosen.min.css'); 
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/chosen/chosen.jquery.min.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/ead/publicacao.js');
        
        
        $this->view->form = $this->form;
        if($this->getRequest()->isPost()) { 
            $formData = $this->getRequest()->getPost();
            try {
                if($this->form->isValid($formData)) {
                    
                    $this->db->beginTransaction();
                    
                    $id = (int) $this->form->getValue($this->_pk);
                    
                    $data = $formData;//$this->form->getValues(); 
                    
                    unset($data['Salvar']);
                    unset($data['destino']);
                    
                    if($id == 0){ 
                        
                        $TPC_ID = isset($data['TPC_ID']) ? implode(',', $data['TPC_ID']):'';
                        $ALU_ID = isset($data['ALU_ID']) ? implode(',', $data['ALU_ID']):'';
                        $CBS_ID = isset($data['CBS_ID']) ? implode(',', $data['CBS_ID']):'';
                        $CUR_ID = isset($data['CUR_ID']) ? implode(',', $data['CUR_ID']):'';
                        
                        $arr = array(
                            'PBC_DATHOR' => date('Y-m-d H:i:00'),
                            'USU_ID'  => Zend_Auth::getInstance()->getStorage()->read()->USU_ID,
                            'TPC_ID'  => $TPC_ID,
                            'ALU_ID'  => $ALU_ID,
                            'CBS_ID'  => $CBS_ID,
                            'CUR_ID'  => $CUR_ID,
                            'PBC_STA' => '1',
                        );
                        $this->db->insert($this->_table,$arr);
                        $id = $this->db->lastInsertId(); 
                        
                        foreach($data['TPC_ID'] as $topico){
                        
                            //alunos
                            if($formData['destino'] == 'a'){
                                foreach($data['ALU_ID'] as $aluno){

                                    $query = 'SELECT SQL_CACHE USU_ID FROM ALUNO WHERE ALU_ID = '.$aluno;
                                    $row = $this->db->fetchRow($query);

                                    $arr2 = array(
                                        'TPC_ID'  => $topico,
                                        'ALU_ID'  => $aluno,
                                        'PBC_ID'  => $id,
                                    );
                                    
                                    if($this->validaTopicoAluno($topico,$aluno))
                                        $this->db->insert('TOPICO_ALUNO',$arr2);
                                }
                            // cursos
                            } else if($formData['destino'] == 'c'){
                                foreach($data['CBS_ID'] as $curso){    

                                    $query = 'SELECT SQL_CACHE DISTINCT m.ALU_ID '
                                            . 'FROM MATRICULA m, CURSO c, CURSOBASE cb '
                                            . 'WHERE m.CUR_ID = c.CUR_ID AND cb.CBS_ID = c.CBS_ID '
                                            . 'AND c.CUR_STA = 1 AND cb.CBS_ID = '.$curso.'';
                                    $result = $this->db->fetchAll($query);

                                    foreach($result as $alu){

                                        $arr2 = array(
                                            'TPC_ID'  => $topico,
                                            'ALU_ID'  => $alu['ALU_ID'],
                                            'PBC_ID'  => $id,
                                        );
                                        
                                        if($this-> validaTopicoAluno($topico,$alu['ALU_ID']))
                                            $this->db->insert('TOPICO_ALUNO',$arr2);
                                    }
                                }
                            //grupos
                            } else if($formData['destino'] == 'g'){
                                foreach($data['CUR_ID'] as $grupo){    

                                    $query = 'SELECT SQL_CACHE DISTINCT m.ALU_ID '
                                            . 'FROM MATRICULA m, CURSO c '
                                            . 'WHERE m.CUR_ID = c.CUR_ID '
                                            . 'AND c.CUR_STA = 1 AND c.CUR_ID = '.$grupo.'';
                                    $result = $this->db->fetchAll($query);

                                    foreach($result as $alu){

                                        $arr2 = array(
                                            'TPC_ID'  => $topico,
                                            'ALU_ID'  => $alu['ALU_ID'],
                                            'PBC_ID'  => $id,
                                        );
                                        
                                        if($this-> validaTopicoAluno($topico,$alu['ALU_ID']))
                                            $this->db->insert('TOPICO_ALUNO',$arr2);
                                    }

                                }
                            }
                            
                        }
                    }
                    else{
                        $this->db->update($this->_table,$data, $this->_pk.' = ' . $id);
                    }
                    
                    $this->db->commit();
                    
                    $this->_helper->redirector('index');
                } else {
                    $this->form->populate($formData);
                }
            } catch(Exception $ex) {
                echo $ex->getMessage();
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                $this->form->populate($formData);
                $this->db->rollBack();
            }
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$this->_pk . ' = ' . $id;
                $data = $this->db->fetchRow($query);
                $this->form->populate($data);
                $this->view->data = $data;
            }
        }
    }

    public function deleteAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $id = $this->_getParam('id', 0);
        if ((int)$id > 0 ) {   
            $this->db->beginTransaction();
            try {
                //$data = array($this->_sta_col => 0);
                //$ok = (bool) $this->obj->update($data, $this->_pk . ' = ' . $id);
                
                $query = 'SELECT SQL_CACHE TPC_ID FROM PUBLICACAO WHERE '.$this->_pk .' = '. $id;
                $row = $this->db->fetchRow($query);
                
                if($row['TPC_ID']> 0){
                    $query = 'SELECT SQL_CACHE a.ALC_ID, a.ALU_ID FROM ALUNO_CONTEUDO a, CONTEUDO c '
                            .' WHERE a.TPC_ID = c.TPC_ID AND a.CON_ID = c.CON_ID '
                            .' AND c.TPC_ID in('.$row['TPC_ID'].')';
                    $result = $this->db->fetchAll($query);
                    foreach($result as $row){
                        $this->db->delete('ALUNO_CONTEUDO','ALC_ID = ' . $row['ALC_ID']);
                    }
                }
                
                $ok = (bool) $this->db->delete('TOPICO_ALUNO',$this->_pk . ' = ' . $id);
                $ok = (bool) $this->db->delete($this->_table,$this->_pk . ' = ' . $id);
                
                $this->db->commit();
            } catch(Exception $ex) {
                //echo getMessage();
                $ok = FALSE;
                $msg = 'Não é possível excluir o material!';
                $this->db->rollBack();
            }      
        }       
        echo json_encode(array('ok' => $ok,'msg'=>$msg));
    }
    
    public function validaTopicoAluno($topico,$aluno) {
        
        $query = 'SELECT SQL_CACHE ALU_ID FROM TOPICO_ALUNO WHERE TPC_ID = '.$topico.' AND ALU_ID = '.$aluno;
        $row = $this->db->fetchRow($query);
        if($row['ALU_ID'] > 0 ) return false;
        else return true;
        
    }
}